<template>
  <div id="home">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航 -->
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="value"
            clearable
            @clear="hendleClear"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="add">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table stripe border :data="userList" style="width: 100%">
        <el-table-column type="index" label="序列号" width="80">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="handleState(scope.row)"
            >
            </el-switch>
            {{ scope.row.mg_state }}</template
          >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope.row)"
            ></el-button>
            <el-button
            @click="handleDelede(scope.row)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                 @click="handleRight(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格 -->
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 卡片 -->
    <!-- 添加用户的展示框 -->
    <el-dialog
      title="提示"
      :visible.sync="addUserDialogVisible"
      width="30%"
     
    >
     <!-- 主体信息 -->
     <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="80px" >
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addUserForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addUserForm.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addUserForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机号码" prop="mobile">
    <el-input v-model="addUserForm.mobile"></el-input>
  </el-form-item>
     </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="suerAdd"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑用户的展示框 -->
    <el-dialog
  title="提示"
  :visible.sync="editDialogVisible"
  width="30%"
 >
  <el-form :model="editUserForm" :rules="editRules" ref="editRuleForm" label-width="100px" >
  <el-form-item label="用户名" prop="username">
    <el-input v-model="editUserForm.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="editUserForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机号码" prop="mobile">
    <el-input v-model="editUserForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="cancleUpdata">取 消</el-button>
    <el-button type="primary" @click="suerUpdate(infoId)">确 定</el-button>
  </span>
</el-dialog>
    
    <!-- 分配权限展示框 -->
    <el-dialog
  title="分配角色"
  :visible.sync="settingRoleDialogVisible"
  width="30%"
  >
  <p>当前的用户：{{this.roleInfo.username}}</p>
  <p>当前的角色：{{this.roleInfo.role_name}}</p>
  <!-- 下拉选择 -->
  <el-select v-model="sleectId" placeholder="请选择角色">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  <span slot="footer" class="dialog-footer">
    <el-button @click="settingRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="sruesettingRole">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { getUserList } from "../../api/userList";
import { changeUserState } from "../../api/state";
import {addUser} from '../../api/addUser'
import{queryUserById} from '../../api/queryById'
import{upDateUserInfo}from '../../api/upDateUserInfo'
import {deleteUser} from '../../api/deledeUser'
import {getRoleList} from '../../api/getRolesList'
import {fenPeiRoleRight} from '../../api/fenPeiRoleRight'
export default {
  data() {
    return {
      rolesList:[],
      sleectId:'',
      roleInfo:'',
       settingRoleDialogVisible:false,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userInfo:{},
      userList: [],
      infoId:'',
      total: 0,
      value: "",
      addUserDialogVisible:false,
      addUserForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      addUserRules:{
        username:[
           { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
          password:[
           { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
          email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 8, max: 20, message: '请输入正确的邮箱', trigger: 'blur' }
        ],
           mobile:[
           { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min:11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      editDialogVisible:false,
      editUserForm:{
        username:'',
         email:'',
         mobile:''
      },
      editRules:{
        username: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 8, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 11, max: 11, message: '长度在 11 到 11 个字符', trigger: 'blur' }
          ],
      },
     
    };
  },
  created() {
    this._getUserList();
  },
  methods: {
    async _getUserList() {
      var res = await getUserList(this.queryInfo);

      this.userList = res.data.data.users;
      this.total = res.data.data.total;
    },

    //  当size改变时
    handleSizeChange(newValue) {
      // console.log(newValue)
      // 当size改变时,重新发请求
      this.queryInfo.pagesize = newValue;
      this.queryInfo.pagenum = 1
      this._getUserList();
    },
    // 当页码改变时
    handleCurrentChange(newValue) {
      // console.log(newValue)
      // 当页码改变时
      this.queryInfo.pagenum = newValue;
      this._getUserList();
    },
    // 添加用户
    add() {
       this.addUserDialogVisible = true
    },
    // 点击取消
    cancel(){
        this.addUserDialogVisible = false
        this.$refs.addUserRef.resetFields()
    },
    // 点击了确定
    suerAdd(){
         this.$refs.addUserRef.validate( async valid=>{
           console.log(valid)
           if(!valid){
             this.$message({
                message: '请把表单信息填写完整',
                type: 'warning'
             })
             return
           }
          //  验证通过发起网络请求
          var res = await addUser(this.addUserForm)
          console.log(res)
          if(res.status !=200){
             this.$message({
                message: '添加用户失败',
                type: 'warning'
             })
          }
           this.$message({
                message: '添加用户成功',
                type: 'success'
             })
              this.$refs.addUserRef.resetFields()
              this.addUserDialogVisible = false
              this._getUserList();
         })
        //  this.addUserDialogVisible = false
    },
    // 跟新状态
    async handleState(info) {
      const res = await changeUserState(info.id, info.mg_state);

      if (res.status != 200) {
        info.mg_state = !info.mg_state;
        this.$message.error("更新状态失败");
        return;
      }
      this.$message.success("更新状态成功");
    },
    // 点击搜索
    search() {
      this.queryInfo.query = this.value;
      this._getUserList();
    },
    // 清空搜索框，重新发起请求
    hendleClear() {
      this.queryInfo.query = "";
      this._getUserList();
    },
    // 点击编辑按钮
    async handleEdit(info){
      this.infoId = info.id
      // console.log(info.id)
      this.editDialogVisible = true
     const res = await queryUserById(info.id)
     console.log(res.data.data)
    //  this.userInfo = res.data.data
     this.editUserForm.username = res.data.data.username
     this.editUserForm.mobile = res.data.data.mobile
     this.editUserForm.email = res.data.data.email
    },
    // 点击了取消更新
    cancleUpdata(){
      this.editDialogVisible = false
    },
    // 点击了确定
   async suerUpdate(id){
    //  console.log(id)
       const obj = {
         email:this.editUserForm.email,
         mobile:this.editUserForm.mobile
       }
       const res =await upDateUserInfo(id,obj)
      
       this.editDialogVisible = false
        this.$message.success('更新成功')
        this._getUserList();

    },
    // 点击删除用户
    handleDelede(info){

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await deleteUser(info.id)
         
          this.queryInfo.pagenum = 1
          this._getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 点击分配权限
  async handleRight(roleInfo){
        // console.log(roleInfo)
        // 获取角色列表
       const res = await getRoleList()
   
       this.rolesList = res.data.data
      //  console.log(this.rolesList )
        this.roleInfo = roleInfo
        this.settingRoleDialogVisible = true
    },
    // 点击确定分配权限
    async sruesettingRole(){
         
       const res = await  fenPeiRoleRight(this.roleInfo.id,this.sleectId)
      //  console.log(res)
       this.roleInfo = {}
       this.sleectId = ''
       this.settingRoleDialogVisible = false
        this._getUserList();
     }
  },
};
</script>

<style>
</style>